/*jslint browser: true, devel: true*/
/*global $ window*/
  /**
   ** 前端参数表
   **/
  var CommonParameters = {
    getCfgParamFromOmp: function (){
      var dataExtractReqVo = {
        "dataType": "CfgParam",
        "filters": [
          {
            "name": "orgCode",
            "type": "0",
            "value": Agent.getCurrentAgent().tenantId
          },
          {
            "name": "module",
            "type": "0",
            "value": "EMM"
          }
        ],
        "offset": 0,
        "limit": 100
      };
      var url = CONFIG.restIp + '/eurm/if/data/transfer/list.ptc';
      $.ajax({
        data: JSON.stringify(dataExtractReqVo),
        url: url,
        type: 'post',
        dataType: 'json',
        async: true,
        timeout: CommonApi.ajaxRequestTimeout,
        beforeSend: function (request) {
          request.setRequestHeader('Content-Type', 'application/json');
          request.setRequestHeader('__org', Utils.cookie.readCookie('tenantId') || window.CONFIG.tenantId);
        },
        success: function (data) {
          if(data && data.info.total > 0){
            var uuids = [];
            for (var i = 0; i < data.info.data.length; i++) {
              uuids.push(data.info.data[i].uuid);
            }
            var dataExtractReqVo1 = {
              "dataType": "CfgParamItem",
              "filters": [
                {
                  "name": "configParam",
                  "type": "7",
                  "value": String(uuids)
                }
              ],
              "offset": 0,
              "limit": 1000
            }
            $.ajax({
              data: JSON.stringify(dataExtractReqVo1),
              url: url,
              type: 'post',
              dataType: 'json',
              async: true,
              timeout: CommonApi.ajaxRequestTimeout,
              beforeSend: function (request) {
                request.setRequestHeader('Content-Type', 'application/json');
                request.setRequestHeader('__org', Utils.cookie.readCookie('tenantId') || window.CONFIG.tenantId);
              },
              success: function (data) {
                CommonParameters.getCfgParamItemFromOmp(data)
              }
            })
          }
        }
      });
    },
    getCfgParamItemFromOmp: function(data){
      if(data && data.info.total > 0){
        for (var i = 0; i < data.info.data.length; i++) {
          var paramItem = data.info.data[i];
          var value = paramItem.value;
          if(!value){
            continue;
          }
          var multilingual = paramItem.multilingual;
          switch (paramItem.code) {
            case 'UNICHAT': {
              window.Settings.chat.unichat = value =="true";
              break;
            }
            // 客户未响应提示自动结束时间
            case 'ROLE_CLIENT_TIME_OUT_TIME':
            case 'OVERHINTTIME': {
              window.Settings.chat.sessionTimeLong = parseInt(value) * 60;
              break;
            }
            // 客户未响应结束会话时间
            case 'ROLE_CLIENT_TIME_OUT_PROMPT_TIME':
            case 'MAXNOANSWERTIME': {
              window.Settings.chat.sessionTimeOut = parseInt(value) * 60;
              break;
            }
            case 'TIME_OUT_PROMPT': {
              if(multilingual == '1'){
                transLang.en_US.tip.NoResponse = value.en_US;
                transLang.zh_CN.tip.NoResponse = value.zh_CN;
                transLang.zh_TW.tip.NoResponse = value.zh_TW;
              }else{
                transLang.en_US.tip.NoResponse = value;
                transLang.zh_CN.tip.NoResponse = value;
                transLang.zh_TW.tip.NoResponse = value;
              }
              break;
            }
            case 'ROLE_CLIENT_IN_CHAT_UNSEND_MSG_SYSTEM_END_SESSION_PROMPT': {
              if(multilingual == '1'){
                transLang.en_US.tip.EndChat = value.en_US;
                transLang.zh_CN.tip.EndChat = value.zh_CN;
                transLang.zh_TW.tip.EndChat = value.zh_TW;
              }else{
                transLang.en_US.tip.EndChat = value;
                transLang.zh_CN.tip.EndChat = value;
                transLang.zh_TW.tip.EndChat = value;
              }
              break;
            }
            // 在线自动接听应答
            case 'AUTOANSWER': {
              window.Settings.chat.autoAnswer = value =="true";
              break;
            }
            // 电话自动应答开关
            case 'CALL_AUTO_ANSWER': {
              window.Settings.phone.autoAnswer = value =="true";
              break;
            }
              // 电话振铃弹框位置
            case'RINGBOXPOSITION': {
              Constants.ringScreenBox.ringBoxPosition = value;
              break;
            }
            // 在线振铃弹框位置
            case 'RINGBOXPOSITION_IM': {
              Constants.ringScreenBox.ringBoxPositionIM = value;
              break;
            }
            // 座席签入后是否就绪
            case 'LOGIN_STATUS': {
              window.Settings.chat.autoReady = value;
              break;
            }
            //一次最多发送图片数量
            case 'MAX_IMG_NO': {
              window.Settings.chat.maxImgNo = value;
              break;
            }
            //一次最多发送文件数量
            case 'MAX_FILE_NO': {
              window.Settings.chat.maxFileNo = value;
              break;
            }
            //快捷发送快捷键
            case 'SENDKEY': {
              Constants.quickSend.keyValue = value;
              break;
            }
            //消息提示音乐设置
            case 'MESSAGE_NOTICE': {
              Constants.messageSoundWarning = value;
              break;
            }
            //微信渠道模式
            case 'WECHAT_MODE': {
              Constants.wechatMode = value;
              break;
            }
            //企业微信模式
            case 'WEWORK_MODE': {
              Constants.weworkMode = value;
              break;
            }
            // 电话延迟接听参数(秒)
            case 'CALL_AUTO_ANSWER_WAITTIME': {
              window.Settings.phone.phoneAnswerDelayTimeOut = parseInt(value)*1000;
              break;
            }
            // 多媒体延迟接听参数(秒)
            case 'IM_AUTOANSWER_WAITTIME': {
              window.Settings.chat.chatAnswerDelayTimeOut = parseInt(value)*1000;
              break;
            }
            // 多媒体最大转接次数
            case 'IM_MAX_TRANSFER_NUM': {
              window.Settings.chat.maxTransferNum = parseInt(value);
              break;
            }
            // 多媒体转接、咨询、会议、监听自动接听
            case 'IM_AUTO_ANSWER4TRANSFER': {
              window.Settings.chat.chatTransferAutoAnswer = value =="true";
              break;
            }
            // 座席超时未响应提示语显示时间
            case 'AGENT_NORESPONSE_TIME': {
              window.Settings.chat.agentSessionTimeOut = parseInt(value)*60;
              break;
            }
            // 座席超时未响应提示语
            case 'AGENT_NORESPONSE_PROMPT': {
              if(multilingual == '1'){
                transLang.en_US.tip.AGENT_NORESPONSE_PROMPT = value.en_US;
                transLang.zh_CN.tip.AGENT_NORESPONSE_PROMPT = value.zh_CN;
                transLang.zh_TW.tip.AGENT_NORESPONSE_PROMPT = value.zh_TW;
              }else{
                transLang.en_US.tip.AGENT_NORESPONSE_PROMPT = value;
                transLang.zh_CN.tip.AGENT_NORESPONSE_PROMPT = value;
                transLang.zh_TW.tip.AGENT_NORESPONSE_PROMPT = value;
              }
              break;
            }
            // 座席超时未响应图标变红色显示时间
            case 'CHANGETAB_YELLOW': {
              window.Settings.chat.agentSessionTimeOutYellow = parseInt(value)*60;
              break;
            }
            // 座席超时未响应图标变红色显示时间
            case 'CHANGETAB_RED': {
              window.Settings.chat.agentSessionTimeOutRed = parseInt(value)*60;
              break;
            }
            // 获取座席外呼前缀参数
            case 'PREFIX': {
              window.Settings.phone.outBoundPrefix = parseInt(value);
              break;
            }
            // 服务历史是否需要根据行政组查询
            case 'HISTORY_DATAISOLATION': {
              window.Settings.serviceHistoryDataIsolation = value =="true";
              break;
            }
            case 'NOTICE_INTERVAL': {
              Constants.IntervalList['NOTICE_INTERVAL'] = parseInt(value);
              break;
            }
            case 'CALLBACKLIST_INTERVAL': {
              Constants.IntervalList['CALLBACKLIST_INTERVAL'] = parseInt(value);
              break;
            }
            case 'STATISTIC_INTERVAL': {
              Constants.IntervalList['STATISTIC_INTERVAL'] = parseInt(value);
              break;
            }
            case 'MARQUEE_INTERVAL': {
              Constants.IntervalList['MARQUEE_INTERVAL'] = parseInt(value);
              break;
            }
            // 定时查询外呼预约接口
            case 'OUTBOUND_MSG_INTERVAL': {
              Constants.IntervalList['OUTBOUND_MSG_INTERVAL'] = parseInt(value);
              break;
            }
            // 未接来电列表每页显示条数
            case 'CALLBACK_ALLOCATED_NO': {
              Constants.callbackAllocatedN0 = parseInt(value);
              break;
            }
            // 敏感词检测开关
            case 'SENSITIVECHECK': {
              Constants.sensitiveFlag = value;
              break;
            }
            // 满意度是否必填
            case 'REQUIRED_CHAT_SATISFACTION': {
              window.Settings.chat.requiredChatSatisfaction = value;
              break;
            }
            // 满意度评价次数
            case 'CHAT_SATISFACTION_TIMES': {
              window.Settings.chat.chatSatisfactionTimes = parseInt(value);
              break;
            }
            // 公告数据是否隔离参数
            case 'Notice_DATAISOLATION': {
              window.Settings.noticeDataIsolation = value =="true";
              break;
            }
            // 快捷回复是否显示表情分类
            case 'EmojiManage': {
              window.Settings.emojiManage = value =="true";
              break;
            }
            // 客户标签后+n的次数是否显示
            case 'CUST_LABEL_TIMES': {
              window.Settings.tagNumber = value =="true";
              break;
            }
            case 'END_AFTERCALLWORK_Switch': {
              window.Settings.END_AFTERCALLWORK_Switch = value =="true";
              break;
            }
            case 'END_AFTERCALLWORK_TIME': {
              window.Settings.END_AFTERCALLWORK_TIME = parseInt(value);
              break;
            }
            // 快捷回复中权限是否启用
            case 'QuickReplyAuth': {
              window.Settings.QuickReplyAuth = JSON.parse(value);
              break;
            }
            // 弹屏信息接口类型
            case 'SCREENINF_PORTTYPE': {
              Constants.screenInfoType = value;
              break;
            }
            case 'CHAT_CHANGE_USER': {
              window.Settings.chat.CHAT_CHANGE_USER = value =="true";
              break;
            }
            // 邮箱发件箱模式
            case 'MailMode': {
              window.Settings.mailMode = value;
              break;
            }

            // 顶部收缩按钮是否显示
            case 'NAV_ICON_VISIBLE': {
              window.Settings.navIconVisible = value =="true";
              if (window.Settings.navIconVisible) {
                $(".icon-navicon-div").show()
              } else {
                $(".icon-navicon-div").hide()
              }
              break;
            }
            // 个人中心默认布局
            case 'MYCENTER_LAYOUT': {
              try {
                window.Settings.mycenterLayout = JSON.parse(value)
                // eslint-disable-next-line no-empty
              } catch (e) {}
              break;
            }
            // 是否播报工号
            case 'PlayAgentId': {
              window.Settings.PlayAgentId = value =="true";
              break;
            }
            default:
              break;
          }
        }
      }
    },
    // 获取数据字典
    getDataDictionary:function(dictName,successHandler, errorHandler) {
      var data = {
        "filters": [{
          "cond": "0",
          "name": "code",
          "value": dictName
        }],
        "tenantId": Agent.getCurrentAgent().tenantId
      }
      var url = CONFIG.restIps + '/v1/console/data/list/DataDictionaryOrder/list';
      CommonApi.httpPostRequest(url, data,function (dbResponse) {
        successHandler(dbResponse)
      },function () {
        errorHandler()
      });
    },
    // 获取服务历史支持得渠道
    getHistoryChannel:function(url,successHandler) {
      var dataExtractReqVo = {
        "filters": [{
          "cond": "0",
          "name": "code",
          "value": "ChannelType"
        }],
        "tenantId":Agent.getCurrentAgent().tenantId
      };
      console.log('dataExtractReqVo'+JSON.stringify(dataExtractReqVo))
      var getAuthorityParamRequest = $.ajax({
        url  : url,
        type : "post",
        dataType : "json",
        data : JSON.stringify(dataExtractReqVo),
        timeout : AgentApi.ajaxRequestTimeout,
        async: true,
        beforeSend: function(request) {
          request.setRequestHeader("Content-Type", "application/json");
        },
        success: function (data) {
          successHandler(data);
          // console.log(data)
        },
        error : function(XMLHttpRequest, status, errorThrown) {
          if('timeout' != status) {
            if(Settings.debugAll)  console.log(new Date() + "[log info, 请求异常  " + status + " : " + errorThrown + "]");
          }
        },
        complete : function(XMLHttpRequest, status){
          if("timeout" === status) {
            if(Settings.debugAll)  console.log(new Date() + "[log info, 请求超时 : " + status + "]");
            getAuthorityParamRequest.abort();
            globalUiKit.notify('', i18n.promptMessage.lobibox.requestTimeOut);
          }
        }
      });
    },

    // 获取提示语
    getTenantHint: function() {
      var param = {
        "columns": [{
          "cond": 1,
          "name": "channel",
          "paramType": "",
          "value": 'workbench'
        },
          {
            "cond": 0,
            "name": "tenant_id",
            "paramType": "",
            "value": Agent.getCurrentAgent().tenantId
          }
        ],
        limit: 50,
        offset: 0
      }
      var url = window.CONFIG.restIps + '/v1/console/base/data/tenant_hints/list'
      CommonApi.httpPostRequest(url, param, function (data) {
        if (data) {
          if (data.data && data.data.listData && data.data.listData.length > 0) {
            Constants.hintsMap = data.data.listData || [];
          }
        }
      })
    },
    getTenantHintByTypeEng: function(typeEng){
      var hint = '';
      if(Constants.hintsMap) {
        for (var i = 0; i < Constants.hintsMap.length; i++) {
          if (Constants.hintsMap[i].typeEng == typeEng && Constants.hintsMap[i].words) {
            return Constants.hintsMap[i].words;
          }
        }
      }
      return hint;
    },
    // 获取基础配置信息
    getBasicConfig: function() {
      Constants.basicConfig = {}
      var url = window.CONFIG.restIps + '/v1/console/base/data/v_workbench_basic_configuration/list'
      CommonApi.httpPostRequest(url, {}, function (data) {
        if (data) {
          if (data.data && data.data.listData && data.data.listData.length > 0) {
            if($(".portal-header").find(".logo img").length>0 && data.data.listData[0].topLogo) {
              $(".portal-header").find(".logo img")[0].src = CONFIG.fileServer + '/get?filename=' + data.data.listData[0].topLogo || "assets/style/images/header/logo_zh_CN.png"
            }
            if($("#link-favicon").length > 0 && data.data.listData[0].browserLogo) {
              $("#link-favicon")[0].href = CONFIG.fileServer + '/get?filename=' + data.data.listData[0].browserLogo
            }
            if(data.data.listData[0] && data.data.listData[0].manHeadPortrait){
              data.data.listData[0].manHeadPortrait = CONFIG.fileServer + '/get?filename=' + data.data.listData[0].manHeadPortrait
            }
            if(data.data.listData[0] && data.data.listData[0].womanHeadPortrait){
              data.data.listData[0].womanHeadPortrait = CONFIG.fileServer + '/get?filename=' + data.data.listData[0].womanHeadPortrait
            }
            if(data.data.listData[0] && data.data.listData[0].clientDefaultAvatar){
              data.data.listData[0].clientDefaultAvatar = CONFIG.fileServer + '/get?filename=' + data.data.listData[0].clientDefaultAvatar
            }
            if(data.data.listData[0] && data.data.listData[0].agentDefaultAvatar){
              data.data.listData[0].agentDefaultAvatar = CONFIG.fileServer + '/get?filename=' + data.data.listData[0].agentDefaultAvatar
            }
            if(data.data.listData[0] && data.data.listData[0].anonymousAvatar){
              data.data.listData[0].anonymousAvatar = CONFIG.fileServer + '/get?filename=' + data.data.listData[0].anonymousAvatar
            }
            Constants.basicConfig = data.data.listData[0];
          }
        }
      })
    },
    // 获取渠道接入配置
    getChannelParameter: function() {
      Constants.ChannelParameter = []
      let url = window.CONFIG.restIps + '/v1/console/view/master_sub/channel_parameter/worktime/list'
      let param = {
        masterColumns: [
          {
            cond: 0,
            name: "tenant_id",
            value: "default"
          }
        ]}
      CommonApi.httpPostRequest(url, param, function(data){
        if(data.code == 200 && data.data) {
          Constants.ChannelParameter = data.data;
        }
      });
    },
    getChannelParameterByAppid: function(appid) {
      var channelParameter = {};
      if(Constants.ChannelParameter) {
        for (var i = 0; i < Constants.ChannelParameter.length; i++) {
          if (appid == Constants.ChannelParameter[i].appId) {
            return Constants.ChannelParameter[i];
          }
        }
      }
      return channelParameter;
    },
    getDataDictionaryItemByCode:function(dictName, code) {
      let item = {}
      for (let i = 0; i < Constants.DataDictionary[dictName].length; i++) {
        if (Constants.DataDictionary[dictName][i].content == code) {
          item = Constants.DataDictionary[dictName][i]
          break;
        }
      }
      return item
    },
    getAllDeptByInnerManager: function (responseData,DataDept) {
        DataDept.forEach(item => {
            responseData.forEach(ele => {
              if (item.code == ele.dept) {
                ele.dept = item.name
              }
            })
          })
      return responseData
    },
    getInteractLayout: function() {
      let url = window.CONFIG.restIp + '/v1/agent/agent_personalize/' + Utils.cookie.readCookie('tenantId') + '?agentId=' + Utils.cookie.readCookie('tenantId') + '&userId=' + Utils.cookie.readCookie('userId') + '&configItem=' + 'interactLayOut' + '&configItemValue=';
      CommonApi.httpGetRequest(url,function (data) {
        if (data) {
          if (data && data.retCode === 200) {
            if (data.data.length > 0) {
              try {
                let layout = JSON.parse(data.data[0].configItemValue)
                Settings.interactionWidth = layout.left
              } catch (e) {
                console.log('json parse error ' + JSON.stringify(e))
              }
            }
          }
        }
      })
}
};
